package syscommand

import (
	"errors"
	"strings"
    
    "collecter/app/common/enum"
    "collecter/app/common/helper"
)

type MakeMiddleware struct {
	Middleware string
	BaseCmd
}

func NewMakeMiddleware() *MakeMiddleware {
	return &MakeMiddleware{}
}

func (mc *MakeMiddleware) Configure() {
	// fmt.Println("MakeCtl -> Configure")
	mc.StringVar(&mc.Middleware, "middleware", "", "中间件名称，可以指定包名")
}

func (mc *MakeMiddleware) Execute() error {
	// code ...
	// fmt.Printf("%+v\n", mc)
	if len(mc.Middleware) == 0 {
		return errors.New("中间件名称不能为空")
	}
	path, pkg, middleware, parseErr := mc.ParsePathAndPkg(mc.Middleware, "middleware")
	if parseErr != nil {
		return parseErr
	}
	filename := path + helper.CamelString(middleware, false) + ".go"

	var ctlTplStr string
	tplFile := enum.ROOT_DIR + "console/tpl/middleware.tpl"
	// fmt.Println("tplFile ========== ", tplFile)

	if err, val := helper.ReadFileContent(tplFile, false); err != nil {
		return err
	} else {
		ctlTplStr = val
	}
	// fmt.Println("======= before ======== ", ctlTplStr)

	ctlTplStr = strings.ReplaceAll(ctlTplStr, "{{pkg}}", pkg)
	ctlTplStr = strings.ReplaceAll(ctlTplStr, "{{mdwName}}", middleware)
	// fmt.Println("========= after ========== ", ctlTplStr)

	if err := helper.WriteToFile(filename, ctlTplStr); err != nil {
		return err
	}

	return nil
}
